package com.ikas.autumn.iec104.common.util.object;

import java.io.InputStream;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

/**
 * 类加载
 * @author
 */
public class MyClassLoader extends ClassLoader {
    // jar文件
    private JarFile jarFile;

    public MyClassLoader(JarFile jarFile) {
        this.jarFile = jarFile;
    }

    /**
     * 从某个jar包中加载某个class
     */
    public Class<?> loadOneClass(String name) {
        Class<?> clazz = null;
        try {
            Enumeration<JarEntry> enumeration = jarFile.entries();
            while (enumeration.hasMoreElements()) {
                JarEntry jarEntry = enumeration.nextElement();
                if (jarEntry.getName().endsWith(".class")) {
                    int size = (int) jarEntry.getSize();
                    InputStream in = jarFile.getInputStream(jarEntry);
                    byte[] b = new byte[size];
                    int offset = 0;

                    while (true) {
                        int length = in.read(b, offset, size - offset);
                        offset += length;
                        if (offset >= size) {
                            break;
                        }
                    }

                    String className = jarEntry.getName().substring(0, jarEntry.getName().lastIndexOf("."))
                            .replace("/", ".");

                    @SuppressWarnings("rawtypes")
                    Class result = null;
                    result = super.findLoadedClass(className);
                    if (result == null) {
                        result = defineClass(className, b, 0, size);
                    }

                    if (className.equals(name)) {
                        clazz = result;
                    }
                    in.close();
                }
            }

        } catch (Exception e) {
            return null;
        }

        return clazz;
    }

}
